package com.bz.backend.item.controller;

import com.bz.utils.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String path = "D:/images";
        String originalFilename = file.getOriginalFilename();
        String subPath = "/upload/" + new SimpleDateFormat("yyyyMM").format(new Date()).toString();
        String fileName = path + subPath + "/" + UUID.randomUUID().toString().replace("-","") + originalFilename.substring(originalFilename.lastIndexOf("."));
        File newFile = new File(fileName);
        if (!newFile.exists()){
            newFile.setWritable(true);
            newFile.mkdirs();
        }
        file.transferTo(newFile);
        return Result.ok(fileName);
    }
}
